/*!
// Testweb v0.6.1
// http://or-change.cn
// Copyright 2014 OrChange Inc. All rights reserved.
// Licensed under the GPL License.
*/

/*jslint vars: true, forin: true, plusplus: true */
/*global angular, probe*/
probe.service("Capture", function (uniqueSelector, GET_FRAME) {
	'use strict';

	var context = window;
	var zIndex = 555;

	/**
	 * editor single class
	 * @class editor
	 * @final
	 */
	var editor = {
		cssPath: "",
		curJQ: null
	};
	/**
	 * Capture the DOM after mouse click.
	 * @method catchHTML
	 * @returns {string} A only CSSpath.
	 */
	editor.catchHTML = function (callback) {
		// return a only CSSpath
		this.cssPath = uniqueSelector.gen(this.curJQ[0]);
		if (typeof callback === "function") {
			callback(this.cssPath);
		}
		return this.cssPath;
	};
	/**
	 * Watch each DOM when mouse over.
	 * @method watchHTML
	 */
	editor.watchHTML = function (callback) {
		var markElement, catchElement, drawArea, eraseArea,
			left = 1,
			top = 1,
			that = this;
		var frameOffset = GET_FRAME().getBoundingClientRect();
		that.curJQ = null;

		var $axes = angular.element('<div id="axes"></div>');
		$axes[0].style.zIndex = zIndex;
		var $axesX = angular.element('<hr id="axes-x" />');
		var $axesY = angular.element('<hr id="axes-y" />');
		var $area = angular.element('<div class="area"></div>');
		$axes.append($axesX).append($axesY);

		markElement = function () {
			$axes[0].style.display = 'none';
			var current_element;
			$axesX[0].style.left = left + "px";
			$axesY[0].style.top = top + "px";
			current_element = angular.element(
				context.document.elementFromPoint(left - frameOffset.left, top - frameOffset.top));
			if (that.curJQ !== current_element && current_element[0]) {
				that.curJQ = current_element;
				eraseArea();
				drawArea();
			}
			$axes[0].style.display = '';
		};

		catchElement = function () {
			$axes.remove();
			that.catchHTML(callback);
		};

		drawArea = function () {
			var ele = that.curJQ;
			var offset = ele[0].getBoundingClientRect();//offset within iframe
			// -2 for border
			$area[0].style.top = (offset.top + frameOffset.top - 2) + 'px';
			$area[0].style.left = (offset.left + frameOffset.left - 2) + 'px';
			$area[0].style.width = offset.width + 'px';
			$area[0].style.height = offset.height + 'px';

			$area[0].style.display = '';

			$axes.append($area);
		};

		eraseArea = function () {
			$area[0].style.display = 'none';
		};

		angular.element(window.document.body).append($axes);

		$axes.on('mousemove', function (event) {
			left = event.pageX;
			top = event.pageY;
			markElement();
		});

		$axes.on('click', function () {
			catchElement();
		});

	};


	return angular.extend(editor, {
		setContext: function (newWindow) {
			context = newWindow;
			return this;
		},
		setZIndex: function (newIndex) {
			zIndex = newIndex;
			return this;
		}
	});
});
